<template>
  <div class="report-wrapper loan-data">
    <div class="main-hd">
      <h2>{{ $t("m.loanData") }}</h2>
    </div>
    <div class="main-bd">
      <div class="content-wrap">
        <div class="search-con">

          <div class="items">
            <div class="label">{{$t('m.dayTime')}}</div>
            <DatePicker type="daterange" :options="disDate" :value="TimeDefault" format="yyyy-MM-dd" :placeholder="this.$t('m.pst')" style="width: 200px;" @on-change="handleDatePicker"></DatePicker>
          </div>
          <div style="margin:10px 0;padding-bottom:10px;">
            <Button class="parameter_button" style="margin-right:30px;" @click="queryDateEvent(),handleFilter(),getPlatfromselect()">{{$t('m.recycle')}}</Button>
            <Button class="parameter_button" type="primary" @click="handleFilter(),getPlatfromselect()">{{$t('m.cháxún')}}</Button>

            <Button type="primary" @click="exportData" style="float: right; margin: 4px;" v-if="adminType != 16">
              <Icon type="ios-download-outline"></Icon>
              {{ this.$t("m.exportData") }}
            </Button>
          </div>
        </div>
        <div class="table-con" style="margin-top: 10px">
          <h3 class="table-title">{{ this.$t("m.loanDataP") }}</h3>
          <Table border disabled-hover :columns="loanColumns" :data="channelList" :loading="loanLoading" class="loan-table"></Table>
        </div>
        <div class="table-con">
          <h3 class="table-title">
            {{ this.$t("m.dayDate") }}
          </h3>

          <Table border :columns="loanDetailColumns" :data="loanDetail" :loading="loanDetailLoading"></Table>
          <Page style="float:right;margin:10px 0;" :total="total" :current.sync="page" :page-size-opts="[10, 20, 40, 80, 100]" show-total show-elevator show-sizer @on-change="handleCurrentChange" @on-page-size-change="handleSizeChange"></Page>
        </div>
      </div>
    </div>
  </div>
</template>
<!--      {{this.$t('m.rLstate')}}-->
<script>
import qs from 'qs'
import excel from '@/static/excel'
import tablePoptip from './components/tablePoptip.vue'
import mixin from './mixin'

export default {
  name: 'loanData',
  mixins: [mixin],
  data () {
    return {
      expand: false,
      sort: false,
      platformId: '',
      page: 1,
      pgeSize: 10,
      investorId: '',
      selectDate: [],
      beginDate: '',
      endDate: '',
      investorList: [],
      channelList: [], // platform list
      loanListTotal: [],
      loanSubList: [],
      loanList: [], // loan list
      loanDetail: [], // loan detail list
      TimeDefault: [],
      loanColumns: [{
        title: this.$t('m.channel'),
        key: 'platformName'
      },
      {
        title: this.$t('m.hlm'),
        key: 'orderCount',
        className: 'mouse-hover',
        sortable: true,
        render: (h, params) => {
          let param = params.row
          return h('div', [
            h(tablePoptip, {
              props: {
                text: param.orderCount,
                content: [{
                  key: this.$t('m.shǒujièbǐshù'),
                  value: param.firstOrderCount
                }, {
                  key: this.$t('m.fùjièbǐshù'),
                  value: param.repeatOrderCount
                }]
              }
            })
          ])
        }
      },
      {
        title: this.$t('m.contractM'),
        key: 'loanAmount',
        sortable: true,
        render: (h, params) => {
          let money = parseFloat(params.row.loanAmount)
          return h('div', this.thousandsFormatter(money))
        },
        sortMethod: (a, b, type) => {
          return this.sortAmount(a, b, type)
        }
      },
      {
        title: this.$t('m.rLm'),
        key: 'payAmount',
        sortable: true,
        render: (h, params) => {
          let money = parseFloat(params.row.payAmount)
          return h('div', this.thousandsFormatter(money))
        }
      },
      {
        title: this.$t('m.jqNum'),
        key: 'repayCount',
        className: 'mouse-hover',
        sortable: true,
        render: (h, params) => {
          let param = params.row
          return h('div', [
            h(tablePoptip, {
              props: {
                text: param.repayCount,
                content: [{
                  key: this.$t('m.shǒujièjiéqīngbǐshù'),
                  value: param.firstRepayCount
                }, {
                  key: this.$t('m.fùjièjiéqīngbǐshù'),
                  value: param.repeatRepayCount
                }]
              }
            })
          ])
        }
      },
      {
        title: this.$t('m.clearM'),
        key: 'repayAmount',
        sortable: true,
        render: (h, params) => {
          let money = parseFloat(params.row.repayAmount)
          return h('div', this.thousandsFormatter(money))
        },
        sortMethod: (a, b, type) => {
          return this.sortAmount(a, b, type)
        }
      },
      // {
      //   title: '展期单数',
      //   key: 'extendOrderCount'
      // },
      // {
      //   title: '展期次数',
      //   key: 'extendCount'
      // },
      // {
      //   title: '展期金额',
      //   key: 'discountExtendFee',
      //   render: (h, params) => {
      //     let money = parseFloat(params.row.discountExtendFee) || '';
      //     return h('div', this.thousandsFormatter(money))
      //   }
      // },
      {
        title: this.$t('m.overdueM'),
        key: 'overdueCount'
      },
      {
        title: this.$t('m.overdueRate'),
        key: 'overdueRate',
        sortable: true,
        render: (h, params) => {
          const {
            overdueRate
          } = params.row
          return h('span', this.numberFormatter(overdueRate))
        }
      },
      {
        title: this.$t('m.běnjīnhuíshōulǜ'),
        key: 'repayRate',
        sortable: true,
        renderHeader: (h, params) => {
          return h('span', [
            h('Tooltip', {
              props: {
                transfer: true,
                content: this.$t('m.huíkuǎnjīné') + '/' + this.$t('m.rLm')
              }
            }, [
              h('span', this.$t('m.běnjīnhuíshōulǜ')),
              h('Icon', {
                props: {
                  type: 'ios-help-circle',
                  size: 14
                },
                style: {
                  marginTop: '-2px',
                  verticalAlign: 'middle'
                }
              })
            ])
          ])
        },
        render: (h, params) => {
          const {
            repayRate
          } = params.row
          return h('span', this.numberFormatter(repayRate))
        }
      },
      {
        title: this.$t('m.yínglìjīné'),
        key: 'profitAmount',
        sortable: true,
        render: (h, param) => {
          return h("div", param.row.profitAmount == null ? 0 : param.row.profitAmount);
        }
      },
      ],
      loanLoading: false,
      loanDetailLoading: false,
      loanDetailColumns: [{
        title: this.$t('m.fdrq'),
        key: 'dateStr'
      },
      {
        title: this.$t('m.hlm'),
        key: 'orderCount',
        className: 'mouse-hover',
        render: (h, params) => {
          let param = params.row
          return h('div', [
            h(tablePoptip, {
              props: {
                text: param.orderCount,
                content: [{
                  key: this.$t('m.shǒujièbǐshù'),
                  value: param.firstOrderCount
                }, {
                  key: this.$t('m.fùjièbǐshù'),
                  value: param.repeatOrderCount
                }]
              }
            })
          ])
        }
      },
      {
        title: this.$t('m.contractM'),
        key: 'loanAmount',
        render: (h, params) => {
          let money = parseFloat(params.row.loanAmount)
          return h('div', this.thousandsFormatter(money))
        }
      },
      {
        title: this.$t('m.rLm'),
        key: 'payAmount',
        render: (h, params) => {
          let money = parseFloat(params.row.payAmount)
          return h('div', this.thousandsFormatter(money))
        }
      },
      // {title:"结清笔数",key:'repayCount'},
      {
        title: this.$t('m.jqNum'),
        key: 'repayCount',
        className: 'mouse-hover',
        render: (h, params) => {
          let param = params.row
          return h('div', [
            h(tablePoptip, {
              props: {
                text: param.repayCount,
                content: [{
                  key: this.$t('m.shǒujièjiéqīngbǐshù'),
                  value: param.firstRepayCount
                }, {
                  key: this.$t('m.fùjièjiéqīngbǐshù'),
                  value: param.repeatRepayCount
                }]
              }
            })
          ])
        }
      },
      {
        title: this.$t('m.clearM'),
        key: 'repayAmount',
        render: (h, params) => {
          let money = parseFloat(params.row.repayAmount)
          return h('div', this.thousandsFormatter(money))
        }
      },
      {
        title: this.$t('m.overdueM'),
        key: 'overdueCount'
      },
      {
        title: this.$t('m.overdueRate'),
        key: 'overdueRate',
        render: (h, params) => {
          const {
            overdueRate
          } = params.row
          return h('span', this.numberFormatter(overdueRate))
        }
      },
      {
        title: this.$t('m.běnjīnhuíshōulǜ'),
        key: 'repayRate',
        sortable: true,
        renderHeader: (h, params) => {
          return h('span', [
            h('Tooltip', {
              props: {
                transfer: true,
                content: this.$t('m.huíkuǎnjīné') + '/' + this.$t('m.rLm')
              }
            }, [
              h('span', this.$t('m.běnjīnhuíshōulǜ')),
              h('Icon', {
                props: {
                  type: 'ios-help-circle',
                  size: 14
                },
                style: {
                  marginTop: '-2px',
                  verticalAlign: 'middle'
                }
              })
            ])
          ])
        },
        render: (h, params) => {
          const {
            repayRate
          } = params.row
          return h('span', this.numberFormatter(repayRate))
        }
      },
      {
        title: this.$t('m.yínglìjīné'),
        key: 'profitAmount',
        sortable: true,
        render: (h, param) => {
          return h("div", param.row.profitAmount == null ? 0 : param.row.profitAmount);
        }
      },
      ],
      pageSize: 10,
      page: 1,
      total: 0,
      adminType: '',
      loanProductNo: '',
      loanProductNoList: [],
      // 日期 限制
      disDate: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now()
        }
      }
    }
  },
  created () {
    this.adminType = localStorage.getItem('type')

    this.queryDateEvent()
    this.getLoanProductsList()
    this.getPlatfromselect()
    this.getPlatformList()
  },
  mounted: function () {
    this.getPlatformList()
    this.getPlatfromselect()
  },
  methods: {

    queryDateEvent () {
      var d = new Date();
      let y = d.getFullYear(); // 年份
      let m = (d.getMonth() + 1).toString().padStart(2, '0'); // 月份
      let r = d.getDate().toString().padStart(2, '0'); // 日子
      let h = d.getHours().toString().padStart(2, '0'); // 小时 
      let mm = d.getMinutes().toString().padStart(2, '0'); // 分钟
      let ss = d.getSeconds().toString().padStart(2, '0'); // 秒
      this.beginDate = `${y}-${m}-${r}`; // es6 字符串模板
      this.endDate = `${y}-${m}-${r}`;
      this.TimeDefault = [`${y}-${m}-${r}`, `${y}-${m}-${r}`]
      // this.repayForm.repayDate = this.hksjsaleDate
    },



    getPlatfromselect () {

      let param = {},
        query = ''
      param.beginDate = this.beginDate
      param.endDate = this.endDate
      // param.platformId = this.platformId
      Object.keys(param).forEach((item, index) => {
        if (param[item]) {
          query += `${index === 0 ? '' : '&'}${item}=${param[item]}`
        }
      })
      let url = `/api/laocai/report/order/platform?${query}`
      this.$http.get(url).then((res) => {
        if (res.body.code == 0) {
          if (res.body.result) {
            this.channelList = res.body.result
          } else {
            this.channelList = []
          }
        }
        this.$Message.success(this.$t('m.errorCode' + res.body.code));
      })
    },
    getItemValue () { // 下拉框点击触发
      this.getLoanProductsList()
    },
    // 获取渠道
    getAllInverstorList () {
      this.$http.post('/helsinki/admin/investor/getAllInvestorList')
        .then(({}) => {
          if (errcode === 0) {
            this.investorList = data.list
            if (this.investorList.length === 1) {
              this.investorId = this.investorList[0].investorId
            } else {
              this.investorId = -1
            }
          }
        }, error => {
          console.log(error)
        })
    },
    // 订单汇总数据汇总-第一个表格：第一个
    getPlatformList () {
      let param = {},
        query = ''
      param.beginDate = this.beginDate
      param.endDate = this.endDate
      param.platformId = this.platformId
      Object.keys(param).forEach((item, index) => {
        if (param[item]) {
          query += `${index === 0 ? '' : '&'}${item}=${param[item]}`
        }
      })
      var url1 = `/api/laocai/report/traffic/list?${query}`

      this.$http.get(url1)
        .then((Response) => {
          this.loanList = Response.body.result.list
          // this.channelList = Response.body.result
          this.loanSubList = Response.body.result
          this.loanLoading = false
          //   if (Response.body.code == 0) {
          //   let total = Response.body.result.list.total
          //   this.loanListTotal = [total];
          //   this.loanSubList = Response.body.result;
          //   if (this.platformId == -1) {
          //     this.loanList = this.loanListTotal;
          //     this.expand = false;
          //   } else {
          //     this.loanList = this.loanSubList;
          //     this.expand = true;
          //   }
          // }
        }, error => {
          console.log(error)
        })
    },
    // 获取贷款数据汇总--第二个日期选择
    // getLoanList() {
    //   debugger
    //   var beginDate = this.beginDate
    //   var endDate = this.endDate
    //   // var platformId =  this.platformId

    //   this.$http.get('/api/laocai/report/traffic/list' + '?' + 'beginDate' + '=' + beginDate + '&' + 'endDate' + '=' + endDate
    //       //   {
    //       //   platformId: this.platformId,
    //       //   beginDate: this.beginDate,
    //       //   endDate: this.endDate,
    //       //   investorId: this.investorId,
    //       //   loanProductNo: this.loanProductNo
    //       // }

    //     )
    //     .then((Response) => {
    //       this.loanList = Response.body.result
    //       //   if (Response.body.code == 0) {
    //       //   let total = Response.body.result.total
    //       //   this.loanListTotal = [total];
    //       //   this.loanSubList = data.list;
    //       //   if (this.platformId == -1) {
    //       //     this.loanList = this.loanListTotal;
    //       //     this.expand = false;
    //       //   } else {
    //       //     this.loanList = this.loanSubList;
    //       //     this.expand = true;
    //       //   }
    //       // }
    //       this.loanLoading = false
    //     }, error => {
    //       console.log(error)
    //     })
    // },
    // 该项目的两个 表数据接口两个 ，也有对应的两个日期选择接口
    // 获取用户详情--第一个日期选择
    // getLoanDetail() {
    //   var url = '/api/laocai/report/order/day' + '?' + 'beginDate' + '=' + beginDate + '&' + 'endDate' + '=' + endDate + '&' + 'pageNumber' + '=' + this.page + '&' + 'pageSize' + '=' + pageSize
    //   this.$http.get(url)
    //     .then((Response) => {
    //       // this.loanDetail = Response.body.result
    //       // page
    //       //             this.loanDetail = Response.body.result.list
    //       //             this.total = Response.body.result.size
    //       // this.beginDate=beginDate
    //       // this.endDate=endDate
    //       // console.log(endDate)
    //       if (Response.body.code == 0) {
    //         // this.loanDetail =  Response.body.result.list;
    //         this.total = Response.body.result.size
    //       } else {
    //         this.loanDetail = []
    //         this.total = 0
    //       }
    //     }, error => {
    //       console.log(error)
    //     })
    // },

    // handleSortChange(params) {
    //   if (this.platformId === -1) {
    //     if (this.expand) return
    //     this.expand = true
    //     this.loanList = this.expand ? this.loanList.concat(this.loanSubList) : this.loanListTotal
    //   }
    // },
    handleDatePicker (val) {
      if (this.platformId == -1) {
        this.expand = false
      };
      if (Array.isArray(val)) {
        this.beginDate = val[0]
        this.endDate = val[1]
        this.selectDate = val
      } else {
        this.beginDate = ''
        this.endDate = ''
        this.selectDate = []
      }
    },
    handleFilter () {
      this.loanLoading = false
      this.loanDetailLoading = false
      this.page = 1
      this.getPlatformList() // 第一个
      this.getLoanProductsList() // 第二个
      // this.getLoanList();
      // this.getPlatfromselect();//下拉获取渠道名称
    },
    // 页码改变的回调，返回改变后的页码
    handleCurrentChange (val) {
      // this.loanDetailLoading = true;
      this.page = val
      this.getLoanProductsList()
    },
    // 切换每页条数时的回调，返回切换后的每页条数
    handleSizeChange (val) {
      // this.loanDetailLoading = true;
      this.pageSize = val
      // this.getLoanDetail();
      this.getLoanProductsList()
    },
    // 导出用户数据汇总Excel
    exportData (type) {
      let loanLists = this.channelList
      let loanDetails = this.loanDetail
      loanLists.forEach(element => {
        element.overdueRate = `${(parseFloat(element.overdueRate) * 100).toFixed(2)}%`
        element.repayRate = `${(parseFloat(element.repayRate) * 100).toFixed(2)}%`
      });
      loanDetails.forEach(element => {
        element.overdueRate = `${(parseFloat(element.overdueRate) * 100).toFixed(2)}%`
        element.repayRate = `${(parseFloat(element.repayRate) * 100).toFixed(2)}%`
      });
      if (this.loanDetail.length) {
        const params = {
          title: [
            this.$t('m.channel'),
            this.$t('m.hlm'),
            this.$t('m.contractM'),
            this.$t('m.rLm'),
            this.$t('m.jqNum'),
            this.$t('m.clearM'),
            this.$t('m.overdueM'),
            this.$t('m.overdueRate'),
            this.$t('m.rLrate'),
          ],
          key: [
            'platformName',
            'orderCount',
            'loanAmount',
            'payAmount',
            'repayCount',
            'repayAmount',
            'overdueCount',
            'overdueRate',
            'repayRate',
          ],
          data: loanLists,
          autoWidth: true,
          filename: this.$t('m.loanDataP')
        }
        const paramsSum = {
          title: [
            this.$t('m.fdrq'),
            this.$t('m.hlm'),
            this.$t('m.contractM'),
            this.$t('m.rLm'),
            this.$t('m.jqNum'),
            this.$t('m.clearM'),
            this.$t('m.overdueM'),
            this.$t('m.overdueRate'),
            this.$t('m.rLrate'),
          ],
          key: [
            'dateStr',
            'orderCount',
            'loanAmount',
            'payAmount',
            'repayCount',
            'repayAmount',
            'overdueCount',
            'overdueRate',
            'repayRate',
          ],
          data: this.loanDetail,
          autoWidth: true,
          filename: this.$t('m.dayDate')
        }
        excel.export_array_to_excel(paramsSum)
        excel.export_array_to_excel(params)

        this.getPlatformList()
        this.getPlatfromselect()

      } else {
        this.$Message.info(this.$t('m.biǎogéshùjùbùnéngwéikōng'))
      }
    },
    sortAmount (a, b, type) {
      let aa = parseFloat(a),
        bb = parseFloat(b)

      if (type === 'desc') {
        return aa < bb ? 1 : -1
      } else return aa > bb ? 1 : -1
    },

    // 第一个接口需要传日期，第二个接口page和日期
    // 获取产品列表-每日贷款详情：第二个
    getLoanProductsList () {
      let param = {},
        query = ''
      param.beginDate = this.beginDate
      param.endDate = this.endDate
      param.platformName = this.platformName
      param.pageNumber = this.page
      param.pageSize = this.pageSize
      param.platformId = this.platformId

      Object.keys(param).forEach((item, index) => {
        if (param[item]) {
          query += `${index === 0 ? '' : '&'}${item}=${param[item]}`
        }
      })
      var url1 = `/api/laocai/report/order/day?${query}`

      this.$http.get(url1)
        .then((Response) => {
          if (Response.body.code === 0) {
            this.loanDetail = Response.body.result.list
            this.total = Response.body.result.size
            // this.loanProductNoList = Response.body.result.data;
            if (this.loanProductNoList.length == 1) {
              this.loanProductNo = this.loanProductNoList[0].loanProductNo
            } else {
              this.loanProductNo = 'all'
            }
          }
        }, error => {
          console.log(error)
        })
    }
  }
}
</script>

<style lang="scss">
@import "../../static/style.css";
@import "../../static/common.scss";
.items {
  display: inline-block;
  margin-bottom: 10px;
  margin-right: 20px;
  width: 200px;
  .label {
    overflow: hidden;
    white-space: inherit;
    text-align: right;
    color: #222;
    font-size: 14px;
    margin-right: 10px;
  }
}

  h3 {
    font-size: 16px;
    font-family: PingFang-SC-Heavy, PingFang-SC;
    font-weight: 800;
    color: rgba(34, 34, 34, 1);
    height: 20px;
    padding-left: 8px;
    display: inline-block;
    margin-bottom: 20px;
    background: linear-gradient(
      to right,
      #2d8cf0 0%,
      #2d8cf0 3px,
      #f9f9f9 3px,
      #f9f9f9 100%
    );
  }
</style>